package com.eascs.crm.server.manger.impl;

import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.crm.common.entity.CustomerBasicInfoEntity;
import com.eascs.crm.common.entity.CustomerOpLog;
import com.eascs.crm.common.entity.CustomerUnit;
import com.eascs.crm.common.vo.QueryCustomerVO;
import com.eascs.crm.server.manger.ICustomerInfoManager;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.service.sequence.SequenceService;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.fasterxml.jackson.databind.ObjectMapper;

import jodd.util.StringUtil;

@Repository
public class CustomerInfoManagerImpl extends BaseDao implements ICustomerInfoManager {

	@Reference
	private SysOrgService sysOrgService;
	@Reference
	private SequenceService sequenceService;

	private final Logger logger = LoggerFactory.getLogger(CustomerInfoManagerImpl.class);
	// 重构saveLog方法
	private void saveLogRefactor(String customerid, String opPsn, String type, String up, String down) {
		// 保存操作日志
		CustomerOpLog log = new CustomerOpLog();
		try {
			log.setCustomerid(customerid);
			log.setOpPsn(opPsn);
			log.setOpType(type);
			log.setOpDate(new Date());
			log.setOpContentUp(up);
			log.setOpContentDown(down);
			this.saveEntity(log);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
	public String addCustomer(CustomerBasicInfoEntity customerBasicInfoEntity) {
		Date date = new Date();
		customerBasicInfoEntity.setCreateDate(date);
		customerBasicInfoEntity.setModifyDate(date);
		customerBasicInfoEntity.setCustomerSource(1);
		User user = UserHolder.getUser();
		if (user != null) {
			customerBasicInfoEntity.setCreator(UserHolder.getUser().getCname());
			customerBasicInfoEntity.setModifier(UserHolder.getUser().getCname());
		}
		boolean flag = this.saveEntity(customerBasicInfoEntity);

		ObjectMapper mapper = new ObjectMapper();
		try {
			saveLogRefactor(customerBasicInfoEntity.getCustomerId(), UserHolder.getUser().getCname(), "新增客户基本信息", null,
					mapper.writeValueAsString(customerBasicInfoEntity));
			// saveLog(UserHolder.getUser().getCname(),"新增客户基本信息",null,mapper.writeValueAsString(customerBasicInfoEntity));
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (flag == true) {
			return customerBasicInfoEntity.getCustomerId();
		} else {
			return null;
		}
	}

	@Override
	public boolean updateCustomer(CustomerBasicInfoEntity customerBasicInfoEntity) {
		Date date = new Date();
		customerBasicInfoEntity.setModifyDate(date);
		User user = UserHolder.getUser();
		if (user != null) {
			customerBasicInfoEntity.setModifier(UserHolder.getUser().getCname());
		}

		ObjectMapper mapper = new ObjectMapper();
		try {
			saveLogRefactor(customerBasicInfoEntity.getCustomerId(), UserHolder.getUser().getCname(), "修改客户基本信息",
					mapper.writeValueAsString(
							getById(CustomerBasicInfoEntity.class, customerBasicInfoEntity.getCustomerId())),
					mapper.writeValueAsString(customerBasicInfoEntity));
			// saveLog(UserHolder.getUser().getCname(),"修改客户基本信息",mapper.writeValueAsString(getById(CustomerBasicInfoEntity.class,customerBasicInfoEntity.getCustomerId())),mapper.writeValueAsString(customerBasicInfoEntity));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return this.updateEntity(customerBasicInfoEntity);
	}

	@Override
	public PageResult<CustomerBasicInfoEntity> findCustomerBaseInfo(QueryCustomerVO vo) {
		
			SqlPageQuery<CustomerBasicInfoEntity> sqlPageQuery = new SqlPageQuery<>(CustomerBasicInfoEntity.class, vo.getPageSize(), vo.getShowPage());

			StringBuilder sql = new StringBuilder();
			// sql.append("select
			// t.customer_id,t.customer_code,t.customer_name,t.mobile_number,
			// t.id_number,t.customer_sd_name,"
			// crm-10050 客户列表查询手机号和身份证号脱敏处理（版本20161109调整工单计划）
			/*
			 * sql.append(
			 * "select t.customer_id,t.customer_code,t.customer_name,CONCAT( LEFT (t.mobile_number, 3), '****', RIGHT (t.mobile_number, 3)), CONCAT( LEFT (t.id_number, 3), '****', RIGHT (t.id_number, 3)),t.customer_sd_name,"
			 * + " t.customer_sd from customer_basic_info t where 1=1 " + " and
			 * EXISTS (select 1 from customer_unit u where
			 * /**DATA_PERMISSION(u.unit_id)
			 **/ /* u.customer_id = t.customer_id ) "); */
			sql.append(
					"select t.customer_id,t.customer_name,CONCAT( LEFT (t.mobile_number, 3), '****', RIGHT (t.mobile_number, 3)) as mobile_number, CONCAT( LEFT (t.id_number, 3), '****', RIGHT (t.id_number, 3)) as id_number,t.customer_sd_name,t.customer_code,t.customer_sort"
							+ " from customer_basic_info t  where 1=1 "
							+ " and EXISTS (select 1 from customer_unit u where /**DATA_PERMISSION(u.unit_id)**/ u.customer_id = t.customer_id ) ");
			/*
			 * // 客户编号 if (vo.getCustomer_code() != null &&
			 * !"".equals(vo.getCustomer_code())) { sql.append(
			 * " and t.customer_code like ?"); sqlPageQuery.addParam("%" +
			 * vo.getCustomer_code() + "%");
			 * 
			 * }
			 */

			// 客户姓名
			if (vo.getCustomer_name() != null && !"".equals(vo.getCustomer_name())) {
				sql.append(" and t.customer_name like ?");
				sqlPageQuery.addParam("%" + vo.getCustomer_name() + "%");

			}
			// 证件类型
			if (vo.getId_type() != null && !"".equals(vo.getId_type())) {
				sql.append(" and t.id_type= ?");
				sqlPageQuery.addParam(vo.getId_type());
			}
			// 证件号码
			if (vo.getId_number() != null && !"".equals(vo.getId_number())) {
				sql.append(" and t.id_number like ?");
				sqlPageQuery.addParam("%" + vo.getId_number() + "%");
			}
			// 手机号

			if (vo.getMobile() != null && !"".equals(vo.getMobile())) {
				sql.append(" and t.mobile_number like ?");
				sqlPageQuery.addParam("%" + vo.getMobile() + "%");
			}
			/*
			 * // 客户sd号 if (vo.getCustomer_sd() != null &&
			 * !"".equals(vo.getCustomer_sd())) { sql.append(
			 * " and t.customer_sd like ?"); sqlPageQuery.addParam("%" +
			 * vo.getCustomer_sd() + "%"); }
			 */

			sqlPageQuery.setQuerySql(sql.toString());
			PageResult<CustomerBasicInfoEntity> customerBasepage = this.findByPage(sqlPageQuery);
			return customerBasepage;
		}
	@Override
	public PageResult<Object[]> findCustomerUnitInfo(String customerId,String unitId) {
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, 1000,0);
		StringBuilder sql = new StringBuilder();
		sql.append("select t.unit_id,t.unit_code,t.unit_name,t.op_time from customer_unit t  where 1=1 ");
		// 客户id
		if (customerId != null && !"".equals(customerId)) {
			sql.append(" and t.customer_id= ?");
			sqlPageQuery.addParam(customerId);
		}
		// 平台id
		if (unitId != null && !"".equals(unitId)) {
			sql.append(" and t.unit_id= ?");
			sqlPageQuery.addParam(unitId);
		}
		sqlPageQuery.setQuerySql(sql.toString());
		PageResult<Object[]> customerBasepage = this.findByPage(sqlPageQuery);
		return customerBasepage;
	}
	
	@Override
	public List<CustomerUnit> getCustomerUnitInfo(String customerId){
		String sql = "select * from customer_unit where customer_id= ? ORDER BY op_time,unit_name";
		List<CustomerUnit> list = this.findEntitys(sql, CustomerUnit.class, customerId);
		return list;
	}
	
	@Override
	public String addCustomerUnit(CustomerUnit customerUnit) {
		boolean flag = this.saveEntity(customerUnit);
		if (flag == true) {
			return customerUnit.getId();
		} else {
			return null;
		}
	}
	@Override
	public String getUnitCount(String customerId) {
		String count = this.findString("select count(0) from customer_unit where customer_id= ?", customerId);
		if (!StringUtil.isNotBlank(count)) {
			count = "0";
		}
		return count;
	}
	@Override
	public boolean delUnit(String unit_id, String customer_id) {
		return this.excuteSql("delete  from customer_unit where unit_id = ? and customer_id=? ", unit_id, customer_id);
	}
	


}
